<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>航班管理</title>
    <!-- 引入 Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>

<body>
<iframe src="../Userframe/top.html" frameborder="0" style="width: 100%; height: 100px;"></iframe>
<div class="container mt-5">

    <!-- 刷新按钮 -->
    <button type="button" class="btn btn-warning mb-3" onclick="loadTicketList()">
        <i class="fa-solid fa-rotate"></i> 刷新
    </button>

    <!-- 搜索车票表单 -->
    <form method="post" class="mb-5" onsubmit="return searchTicket(event)">
        <div class="input-group">
            <label for="searchStartStation" class="input-group-text">出发站:</label>
            <input type="text" id="searchStartStation" name="start_station_name" class="form-control" placeholder="输入出发站">
            <label for="searchEndStation" class="input-group-text">到达站:</label>
            <input type="text" id="searchEndStation" name="end_station_name" class="form-control" placeholder="输入到达站">
            <button type="submit" class="btn btn-secondary">搜索</button>
        </div>
    </form>

    <div id="ticketList">
        <!-- 车票列表将通过 AJAX 动态加载 -->
    </div>
</div>

<!-- 添加车票模态框 -->
<div class="modal fade" id="addTicketModal" tabindex="-1" aria-labelledby="addTicketModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addTicketModalLabel">添加车票</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="addTicketForm">
                    <div class="mb-3">
                        <label for="start_station" class="form-label">出发站:</label>
                        <input type="text" id="start_station" name="start_station" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label for="end_station" class="form-label">到达站:</label>
                        <input type="text" id="end_station" name="end_station" class="form-control" required>
                    </div>
                    <button type="button" class="btn btn-primary" onclick="addTicket()">添加</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- 修改车票模态框 -->
<div class="modal fade" id="updateTicketModal" tabindex="-1" aria-labelledby="updateTicketModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="updateTicketModalLabel">修改车票信息</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="updateTicketForm">
                    <input type="hidden" id="updateTid" name="tid">
                    <div class="mb-3">
                        <label for="updateStartStation" class="form-label">出发站:</label>
                        <input type="text" id="updateStartStation" name="start_station" class="form-control">
                    </div>
                    <div class="mb-3">
                        <label for="updateEndStation" class="form-label">到达站:</label>
                        <input type="text" id="updateEndStation" name="end_station" class="form-control">
                    </div>
                    <div class="mb-3">
                        <label for="updatePrice" class="form-label">价格:</label>
                        <input type="number" id="updatePrice" name="price" class="form-control">
                    </div>
                    <button type="button" class="btn btn-success" onclick="updateTicket()">修改</button>
                    <button type="button" class="btn btn-danger" data-bs-dismiss="modal">取消</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- 引入 Font Awesome -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
<!-- 引入 Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    function showUpdateForm(tid, start_station, end_station, price) {
        document.getElementById('updateTid').value = tid;
        document.getElementById('updateStartStation').value = start_station;
        document.getElementById('updateEndStation').value = end_station;
        document.getElementById('updatePrice').value = price;
        // 显示修改车票模态框
        var modal = new bootstrap.Modal(document.getElementById('updateTicketModal'));
        modal.show();
    }

    function deleteTicket(tid) {
        if (confirm('确定要删除该车票吗？')) {
            var xhr = new XMLHttpRequest();
            xhr.open('POST', '/deleteTicket', true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    if (xhr.responseText === 'true') {
                        showSuccess('操作成功！', '车票已经删除');
                        loadTicketList();
                    } else {
                        showError('操作失败！', '车票删除失败');
                    }
                }
            };
            xhr.send('tid=' + tid);
        }
    }

    function searchTicket(event) {
        // 阻止表单的默认提交行为（页面刷新）
        if (event) {
            event.preventDefault();
        }
        var start_station_name = document.getElementById('searchStartStation').value;
        var end_station_name = document.getElementById('searchEndStation').value;
        document.getElementById('searchStartStation').value = "";
        document.getElementById('searchEndStation').value = "";
        var xhr = new XMLHttpRequest();
        if ((start_station_name === null || start_station_name.trim() === "") && (end_station_name === null || end_station_name.trim() === "")) {
            loadTicketList();
        } else {
            xhr.open('POST', '/ticketsearch', true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    // 解析数据
                    console.log(xhr.responseText)
                    var data = JSON.parse(xhr.responseText);
                    var table = '<table class="table table-striped table-bordered">\n';
                    table += '<thead>\n';
                    table += '<tr>\n';
                    table += '<th>TID</th>\n';
                    table += '<th>出发站</th>\n';
                    table += '<th>到达站</th>\n';
                    table += '<th>价格</th>\n';
                    table += '<th>操作</th>\n';
                    table += '</tr>\n';
                    table += '</thead>\n';
                    table += '<tbody>\n';
                    if (data.rows && data.rows.length > 0) {
                        data.rows.forEach(function (row) {
                            table += '<tr>\n';
                            table += '<td>' + row.tid + '</td>\n';
                            table += '<td>' + row.start_station + '</td>\n';
                            table += '<td>' + row.end_station + '</td>\n';
                            table += '<td>' + row.price + '</td>\n';
                            table += '<td style="width: 140px"><button type="button" class="btn btn-info" onclick="showUpdateForm(' + row.tid + ',\'' + row.start_station + '\',\'' + row.end_station + '\',' + row.price + ')">修改</button> <button type="button" class="btn btn-primary" onclick="deleteTicket(' + row.tid + ')">删除</button></td>\n';
                            table += '</tr>\n';
                        });
                    }
                    table += '</tbody>\n';
                    table += '</table>\n';
                    document.getElementById('ticketList').innerHTML = table;
                }
            };
            xhr.send('start_station_name=' + encodeURIComponent(start_station_name) + '&end_station_name=' + encodeURIComponent(end_station_name));
        }
    }

    function loadTicketList() {
        var xhr = new XMLHttpRequest();
        // 这里假设获取所有车票的接口为 /getAllTicket，你需要根据实际情况修改
        xhr.open('POST', '/selectTicket', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                // 解析数据
                var data = JSON.parse(xhr.responseText);
                var table = '<table class="table table-striped table-bordered">\n';
                table += '<thead>\n';
                table += '<tr>\n';
                table += '<th>TID</th>\n';
                table += '<th>出发站</th>\n';
                table += '<th>到达站</th>\n';
                table += '<th>价格</th>\n';
                table += '<th>操作</th>\n';
                table += '</tr>\n';
                table += '</thead>\n';
                table += '<tbody>\n';
                console.log(data.rows)
                if (data.rows && data.rows.length > 0) {
                    data.rows.forEach(function (row) {
                        table += '<tr>\n';
                        table += '<td>' + row.tid + '</td>\n';
                        table += '<td>' + row.start_station + '</td>\n';
                        table += '<td>' + row.end_station + '</td>\n';
                        table += '<td>' + row.price + '</td>\n';
                        table += '<td style="width: 140px"><button type="button" class="btn btn-info" onclick="showUpdateForm(' + row.tid + ',\'' + row.start_station + '\',\'' + row.end_station + '\',' + row.price + ')">买票</button>';
                        table += '</tr>\n';
                    });
                }
                table += '</tbody>\n';
                table += '</table>\n';
                document.getElementById('ticketList').innerHTML = table;
            }
        };
        xhr.send();
    }

    function updateTicket() {
        var tid = document.getElementById('updateTid').value;
        var start_station = document.getElementById('updateStartStation').value;
        var end_station = document.getElementById('updateEndStation').value;
        var price = document.getElementById('updatePrice').value;

        var xhr = new XMLHttpRequest();
        xhr.open('POST', '/updateTicket', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                if (xhr.responseText === 'true') {
                    showSuccess('操作成功！', '修改车票信息成功！');
                    // 重新加载车票列表
                    loadTicketList();
                    // 关闭模态框
                    var modal = bootstrap.Modal.getInstance(document.getElementById('updateTicketModal'));
                    modal.hide();
                } else {
                    showError('操作失败！', '修改车票信息失败！');
                }
            }
        };
        var data = 'tid=' + tid + '&start_station=' + encodeURIComponent(start_station) + '&end_station=' + encodeURIComponent(end_station) + '&price=' + price;
        xhr.send(data);
    }

    function addTicket() {
        var start_station = document.getElementById('start_station').value;
        var end_station = document.getElementById('end_station').value;

        var xhr = new XMLHttpRequest();
        xhr.open('POST', '/addTicketController', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                if (xhr.responseText === 'true') {
                    var modal = bootstrap.Modal.getInstance(document.getElementById('addTicketModal'));
                    modal.hide();
                    showSuccess('操作成功！', '添加车票成功！');
                    // 重新加载车票列表
                    window.location.reload();
                } else {
                    showError('操作失败！', '添加车票失败！');
                }
            }
        };
        var data ='start_station=' + encodeURIComponent(start_station) + '&end_station=' + encodeURIComponent(end_station);
        xhr.send(data);
    }

    function showSuccess(title, text = '', timer = 3000) {
        Swal.fire({
            icon:'success',
            title: title,
            text: text,
            timer: timer,
            showConfirmButton: false,
            toast: true, // 可选：设置为 Toast 模式（更轻量）
            position: 'top-end', // 可选：位置（右上角）
        });
    }

    function showError(title, text = '', timer = 2000) {
        Swal.fire({
            icon: 'error',
            title: title,
            text: text,
            timer: timer || undefined, // 0 时不设置 timer
            showConfirmButton:!!timer, // 如果 timer=0，显示确认按钮
        });
    }

    // 页面加载时自动加载车票列表
    window.onload = loadTicketList;
</script>
</body>

</html>